import locationBehavior from '../../../../behaviors/location'
import api from '../../../../common/api'
import * as user from '../../../../models/user'
import * as filterConfig from '../../../../models/filter'
import * as transferData from '../../../../models/transferData'
import { dialog } from '../../../../component/userStatusDialog/control'

const DEFAULT_TIME = '7'

Component({
  behaviors: [locationBehavior],
  /**
   * 组件的属性列表
   */
  properties: {
    salesType: {
      type: String,
      value: 'OWERN'
    },
    districtOptions: {
      type: Array,
      value: []
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    usable: true, //当前城市是否开通可用
    cityName: '',
    cityCode: '',
    search: {},
    filterDistrict: {},
    infoTypeCurrent: [],
    subscribed: null, //是否订阅
    houseType: null, //房源类型
    filterDistrictOptions: [],
    filterMore: {
      time: DEFAULT_TIME
    },
    vipBool: false, 
    // 快速收索
    quickSearchList: [{
        value: '1',
        label: '已订阅',
      },
      {
        value: '0',
        label: '未订阅',
      },
      {
        value: 'SALES',
        label: '二手',
      },
      {
        value: 'RENT',
        label: '出租',
      }
    ],
    //列表数据
    list_item: [],
    userLat: '', //用户纬度
    userLng: '', //用户经度
    timeout: null,
  },
  /**
   * 组件的生命周期
   */
  lifetimes: {
    attached: function () {
      getApp().globalData.loginPromise.then(() => {
        user.getVip(true).then((res) => {
          this.setData({
            vipBool: res == '0'
          })
        })

        this.initFilterConfig()
        this.getCurrentCity()
          .then(() => {
            return this.fetchUsable()
          })
          .then(() => {
            this.loadHouse()
          })
      })
    },
  },
  /**
   * 页面的生命周期
   */
  pageLifetimes: {
    show: function () {
      this.data.timeout && clearTimeout(this.data.timeout)
      this.data.timeout = setTimeout(() => {
        this.loadHouse()
      }, 100);

      this.refreshCity()
    },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    // 判断当前城市是否开通
    fetchUsable() {
      return new Promise((resolve, reject) => {
        let {cityCode} = this.data
        api.getOwnerSubscribeCountByCityCode({
          cityCode
        }, (res) => {
          if (res && res.data && res.data.isSuccess) {
            if (res.data.content === 0) {
              this.setData({
                usable: false
              })
            }
            resolve()
          } else {
            reject()
          }
        })
      })
    },

    loadHouse() {
      if (!this.data.usable) return
      this.setData({
        list_item: []
      });
      this.selectComponent("#com-scroll-content").fetchHouse(1, ({
        page,
        pageSize
      }) => {
        return new Promise((resolve, reject) => {
          wx.showLoading({
            title: '加载中...',
          })
          let {
            cityCode,
            houseType,
            filterDistrict,
            filterMore,
            subscribed,
            userLat, //用户纬度
            userLng, //用户经度
          } = this.data
          let newFilterMore = filterConfig.parseFilter(filterMore)
          api.houseOwnerList({
            resblockName: this.data.search.resblockName || '',
            subscribed,
            pageNum: page,
            pageSize: 10,
            areaCode: filterConfig.parseAreaFilter(filterDistrict.district),
            cityCode, //城市编码
            houseType, //房源类型
            bizcircleIdList: filterConfig.parseDistrictFilter(filterDistrict.district), //商圈id
            hdResblockId: this.data.search.hdResblockId || '', //树懒小区id
            areaList: newFilterMore.area, //面积列表
            newExternalTime: newFilterMore.time, //新上时间
            priceList: newFilterMore.price, //二手价格
            rentPriceList: newFilterMore.rentPrice, //出租的价格区间
            shiNumList: newFilterMore.type, //室列表
            nearDistance: newFilterMore.distance, //附近距离
            userLat, //用户纬度
            userLng, //用户经度
          },
          ({
            data
          }) => {
            const content = data.content
            data = {
              ...data,
              content: {
                page: content.pageNum,
                rows: content.list,
                total: content.pages
              },
            }
            data.handleData = (rows) => {
              this.setData({
                list_item: this.data.list_item.concat(rows),
              });
              wx.hideLoading()
            };
            resolve(data);
          }, reject);
        });
      });
    },
    // 拿到定义好的筛选项
    initFilterConfig(type) {
      const { districtOptions } = this.data

      const obj = {
        SALES: {
          id: 'price',
          title: '二手价格区间(万)',
          input: {},
          multi: filterConfig.rangeSalesPriceX
        },
        RENT: {
          id: 'rentPrice',
          title: '出租价格区间(元)',
          input: {},
          multi: filterConfig.rangeRentPriceX
        }
      }

      let jiage;
      if (type) {
        jiage = [obj[type]]
      } else {
        jiage = [obj.SALES, obj.RENT]
      }

      this.setData({
        filterDistrictOptions: [{
          id: 'district',
          cascader: districtOptions
        }],
        filterMoreOptions: [{
            id: 'time',
            title: '时间',
            single: filterConfig.rangeAddTimeX,
            defaultValue: DEFAULT_TIME
          },
          // {
          //   id: 'distance',
          //   title: '距离',
          //   single: filterConfig.rangeDistance
          // },
          ...jiage,
          {
            id: 'area',
            title: '建筑面积',
            input: {},
            multi: filterConfig.rangeArea
          }, {
            id: 'type',
            title: '户型',
            multi: filterConfig.rangeHouseType
          }
        ],
      })
    },

    onSearchChange(e) {
      this.data.timeout && clearTimeout(this.data.timeout)
      this.data.timeout = null
      this.setData({
        search: {
          resblockName: e.detail.type === 'key' ? e.detail.value : '',
          hdResblockId: e.detail.type === 'id' ? e.detail.value : '',
        },
      })
      this.clearFilter()
      this.loadHouse()
    },

    clearFilter() {
      this.setData({
        filterMore: {
          time: DEFAULT_TIME
        },
        filterDistrict: {},
      });
      const child = this.selectComponent("#dropdowns");
      child && child.onClear();
    },

    // 城市筛选
    getCurrentCity() {
      return new Promise((resolve, reject) => {
        this.getCityInfoNew().then(({city, cityCode}) => {
          this.setData({
            cityName: city,
            cityCode: cityCode,
          });
          resolve()
        })
      })
    },
    // 检察城市更新
    refreshCity() {
      let chooseCity = transferData.getData('currentCity')
      transferData.resetData('currentCity')
      if (chooseCity) {
        this.data.timeout && clearTimeout(this.data.timeout)
        this.data.timeout = null
        wx.redirectTo({
          url: `/pages/home/propertyOwner/propertyOwner?tab=${this.data.salesType}`,
        })
      }
      
    },
    // 区域   近30天
    onFilterChange(e) {
      let name = e.currentTarget.dataset.name
      let path = `filter${name}`
      let that = this
      // 选择二手或者出租  展示不一样的
      that.setData({
        infoTypeCurrent: '',
        houseType: ''
      })
      that.initFilterConfig()
    if(e.detail.form.price&&e.detail.form.price.length!==0&&e.detail.form.rentPrice&&e.detail.form.rentPrice.length!==0){
      console.log('二手和出租都选择了')
    } else {
      if(e.detail.form.price&&e.detail.form.price.length!==0){ //选择了二手
        that.setData({
          infoTypeCurrent: ['SALES'],
          houseType: 'SALES'
        })
        that.initFilterConfig('SALES')
      }
      if(e.detail.form.rentPrice&&e.detail.form.rentPrice.length!==0){ //选择了出租
        that.setData({
          infoTypeCurrent: ['RENT'],
          houseType: 'RENT'
        })
        that.initFilterConfig('RENT')
      }
  }
  // 选择距离时 添加经纬度
    if (e.detail.form.distance) {
        that.getWxLocationBe()
          .then((res) => {
            that.setData({
              userLat: res.latitude, //用户纬度
              userLng: res.longitude, //用户经度
              [path]: e.detail.form
            })
            that.loadHouse()
          })
      } else {
        that.setData({
          [path]: e.detail.form
        })
        that.loadHouse()
      }
    },

    // 快捷筛选
    onInfoTypeChange(e) {
      let arr = e.detail
      let subscribed = arr.indexOf('1') > -1
      let ubscribedNot = arr.indexOf('0') > -1
      let sales = arr.indexOf('SALES') > -1
      let rent = arr.indexOf('RENT') > -1

      this.setData({
        infoTypeCurrent: arr,
        subscribed: ((subscribed && ubscribedNot) || (!subscribed && !ubscribedNot)) ? null : subscribed,
        houseType: ((sales && rent) || (!sales && !rent)) ? null : (sales ? 'SALES' : 'RENT')
      })
      this.initFilterConfig(this.data.houseType)
      this.loadHouse()
    },
    // 房东电话
    _confirmEvent(e) {
      console.log(e, '房东电话1')
    },
    // 订阅小区
    _cancelEvent(e) {
      let id = e.detail
      this.isVip('cancelEvent', id, '1')
    },

    // 取消订阅
    _cancelEventX(e) {
      let id = e.detail
      this.isVip('cancelEventX', id, '0')
    },
    
    // 判断是不是会员
    isVip(tmp, id, num) { //vip状态 0:正常 1:禁用 2:到期 3:非会员
      user.getVip(true)
        .then(res => {
          if (res == '0') { //会员
            let that = this
            that.checkOfficialAccount()
              .then(() => {
                if (tmp == 'cancelEvent') { //订阅小区
                  this.doSubscribeResblock(id, num)
                }
                if (tmp == 'cancelEventX') {
                  this.doSubscribeResblock(id, num)
                }
              })
              .catch(() => {
                dialog({
                  dialog: 'allFunctions',
                  confirm: () => {
                    let url = 'https://mp.weixin.qq.com/s/I8sdEESdeHIoKLyYVnDcYQ'
                    wx.navigateTo({
                      url: `/pages/webView/webView?webViewUrl=${url}`
                    })
                  },
                  cancel: () => {
                    wx.showModal({
                      title: '',
                      content: '距离开启业主情报功能只有一步，你是否确定放弃',
                      confirmText: '去完成',
                      cancelText: '残忍放弃',
                      confirmColor: '#F75352',
                      success(res) {
                        if (res.confirm) {
                          let url = 'https://mp.weixin.qq.com/s/I8sdEESdeHIoKLyYVnDcYQ'
                          wx.navigateTo({
                            url: `/pages/webView/webView?webViewUrl=${url}`
                          })
                        }
                      }
                    })
                  }
                })
              })
          } else {
            dialog({
              dialog: res=='3'?'superVip':'due',
              confirm: () => {
                wx.navigateTo({
                  url: '/pages/mine/memberCentre/memberCentre'
                })
              }
            })
          }
        })
    },

    // isSubscribe   1订阅小区  0取消订阅
    doSubscribeResblock(id, num) {
      if (num === '0') {
        wx.showLoading({
          title: '取消订阅...',
        })
      } else {
        wx.showLoading({
          title: '订阅中...',
        })
      }
      return new Promise((resolve, reject) => {
        api.doSubscribeResblock({
          hdResblockId: id,
          isSubscribe: num
        }, (res) => {
          if (res && res.data && res.data.isSuccess) {
            wx.hideLoading()
            const {
              list_item
            } = this.data
            list_item.forEach(item => {
              if (item.hdResblockId === id) {
                item.subscribed = num === '1' ? true : false
              }
            })
            this.setData({
              list_item
            })
            resolve()
          } else {
            wx.hideLoading()
            wx.showModal({
              title: '订阅失败',
            })
            reject()
          }
        })
      })
    },
    // 判断是否关注公众号
    checkOfficialAccount() {
      return new Promise((resolve, reject) => {
        user.getOfficialAccount(true)
          .then(res => {
            if (res === '1') {
              resolve()
            } else {
              reject()
            }
          })
          .catch(() => {
            wx.showToast({
              icon: 'none',
              title: '网络错误，请稍后再试~',
            })
          })
      })
    },
  }
})